<?php

namespace App\Http\Controllers\Api\V1;

use Carbon\Carbon;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Cache;
use App\Supports\Auth\Alipay\AlipayBinder;
use App\Supports\Auth\Alipay\AlipayLogger;
use App\Services\AuthOneDevice\AuthOneDevice;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use App\Http\Controllers\Api\V1\Requests\AuthStoreRequest;
use App\Http\Controllers\Api\V1\Requests\AuthWxminiRequest;
use App\Http\Controllers\Api\V1\Requests\AuthAlipayRequest;
use App\Http\Controllers\Api\V1\Requests\AuthAlipayBindRequest;
use App\Http\Controllers\Api\V1\Requests\AuthWechatBindRequest;
use App\Services\RegisterNewUser\RegisterNewUser;
use App\Supports\Auth\Wechat\WechatLogger;
use App\Models\User;
use App\Supports\Sms\Sms;
use App\Supports\LinkedIn\Client;
use App\Supports\LinkedIn\Scope;
use App\Supports\LinkedIn\AccessToken;



class AuthController extends Controller
{

	protected function getGuzzleClient()
	{
		return new Client(['Content-Type' => 'application/x-www-form-urlencoded']);
	}
	public function store()
	{	
		//$request = app(AuthStoreRequest::class);

		$code = request('code');
		// instantiate the Linkedin client
		$client = new Client(
		    getenv('LINKDIN_CLIENT_ID'),
		    getenv('LINKDIN_CLIENT_SECRET'),
		);
		
		/*$profile = $client->get(
		    'me',
		    ['fields' => 'id,firstName,lastName']
		);*/
		//$client->setRedirectUrl();
		$client->setRedirectUrl('https://www.xbreakingtechinsight.com');
		$accessToken = $client->getAccessToken($code);

		$jsonStr = json_encode($accessToken);
		$tokenData = json_decode($jsonStr, true);
		// instantiate access token object from stored data
		$accessToken = new AccessToken($tokenData['token'], $tokenData['expiresAt']);
	
		//$token = $accessToken['token'];
		$client->setAccessToken($accessToken);

		

		$credentials = [];
		
		$profile = $client->get(
		    'userinfo',
		);

		$user = User::query()->where('name',$profile['name'])->where('nickname',$profile['sub'])->first();
		if($user){
			$credentials['phone'] = $user->phone;
			$credentials['password'] = 000000;

		}else{

			$credentials['phone'] = "1".rand(3,9).rand(00000000,99999999);
			$credentials['password'] = 000000;
		}
		$userToken = auth('api')->setTTL(config('api.auth_ttl'))->attempt($credentials);
		
		

		if($user){

			if ($user->first()->last_token) { 
				try {
					JWTAuth::setToken($user->first()->last_token)->invalidate();
				} catch (TokenExpiredException $e) {}
			}
			
			$user->update(['last_token' => $userToken,'linkdin_token'=>$tokenData['token']]);
		}else{
			
			$avatar = "";
			if(isset($profile['picture'])){

				$avatar = $profile['picture'];
			}
			User::insert(['name'=>$profile['name'],'nickname'=>$profile['sub'],'phone'=>$credentials['phone'],'avatar'=>$avatar,'password'=>bcrypt(000000),'last_token'=>$userToken,'linkdin_token'=>$tokenData['token']]);

			$userToken = auth('api')->setTTL(config('api.auth_ttl'))->attempt($credentials);

		}

		
		return $this->respondWithToken($userToken)->setStatusCode(201);
		//dd($token);
		
	}

	public function getUser()
	{	
		$token = auth('api')->setTTL(config('api.auth_ttl'))->login($user);

		$client = new Client(
		    getenv('LINKDIN_CLIENT_ID'),
		    getenv('LINKDIN_CLIENT_SECRET'),
		);
		$client->setRedirectUrl('https://www.xbreakingtechinsight.com');
		$client->setAccessToken($accessToken);

		$profile = $client->get(
		    'me',
		    ['fields' => 'id,firstName,lastName']
		);
		print_r($profile);

	}



	public function url()
	{
		// instantiate the Linkedin client
		$client = new Client(
		    getenv('LINKDIN_CLIENT_ID'),
		    getenv('LINKDIN_CLIENT_SECRET'),
		);
		$redirectUrl = $client->getRedirectUrl('https://api.xbreakingtechinsight.com');
		$client->setRedirectUrl('https://www.xbreakingtechinsight.com');
		$scope = new Scope();
		$scopes = [
		   'profile',
		   'openid',
		   'w_member_social'
		 // Scope::r_liteprofile
		];
		
		$loginUrl = $client->getLoginUrl($scopes);
		
		return response()->json(['url' => $loginUrl]);
		/*$lock = Cache::lock('send_sms_code', 15);

		try {

			if (!$lock->get()) fail('请稍后重试');

			$request = app(AuthStoreRequest::class);

			$credentials['phone'] = request('phone');
			$credentials['password'] = 000000;


			$token = auth('api')->setTTL(config('api.auth_ttl'))->attempt($credentials);

			$user = User::query()->where('phone',$request->phone);

			if($user->first()){
				if ($user->first()->last_token) { 
					try {
						JWTAuth::setToken($user->first()->last_token)->invalidate();
					} catch (TokenExpiredException $e) {}
				}

				$user->update(['last_token' => $token]);

			}else{
				
				app(RegisterNewUser::class, [
					'phone' => $request->phone,
					'inviteCode' => $request->invite_code
				])->register();

				$credentials['phone'] = request('phone');
				$credentials['password'] = 000000;


				$token = auth('api')->setTTL(config('api.auth_ttl'))->attempt($credentials);
			}
			app(Sms::class)->cleanCachedDataAfterUsing(request('sms_key'));

		} finally {
			$lock->release();
		}

		return $this->respondWithToken($token)->setStatusCode(201);*/
	}

	public function wechat()
    {

	    $user = app(WechatLogger::class)->login();
	    $token = auth('api')->setTTL(config('api.auth_ttl'))->login($user);
	    auth('api')->user()->update(['last_logged_at' => Carbon::now()]);
	    return $this->respondWithToken($token)->setStatusCode(201);
    }


	public function wechatSessionKey()
    {
    	$code =request('code');

    	$data =[
    		'appid'=> 'wxdddbfda965703064',        //你的小程序的APPID
			'secret'=>'5313745e611440b5b5e1af143f3cb326',    //你的小程序秘钥secret,  
			'js_code'=> $code,    //wx.login 登录成功后的code
			'grant_type'=>'authorization_code'
    	];

    	$response = $this->getGuzzleClient()
				->get('https://api.weixin.qq.com/sns/jscode2session', ['query' => $data])->getBody()->getContents();
		
		

		return $response;
    }


	public function alipayPayload()
	{
		$payload = app(AlipayLogger::class)->appPayload();
		return response()->json(['payload' => $payload->getContent()]);
	}

	public function alipay()
	{
		$user = app(AlipayLogger::class)->login();
		$token = auth('api')->setTTL(config('api.auth_ttl'))->login($user);
		auth('api')->user()->update(['last_logged_at' => Carbon::now()]);
		return $this->respondWithToken($token)->setStatusCode(201);
	}

	public function alipayBind()
	{
		$lock = Cache::lock('alipay_bind', 30);

		try {

			if (! $lock->get()) fail('处理中...请勿频繁操作');

			$request = app(AuthAlipayBindRequest::class);
			$user = $request->user();

			need_paycode($user);

			if ($user->isAlipayBound()) {
				fail('支付宝已被其它账号绑定');
			}

			app(AlipayBinder::class)->bind($user);

		} finally {
			$lock->release();
		}

		return response(null, 204);
	}

    public function update()
    {
	    if ($user = auth('api')->user()) {
    	    $token = auth('api')->setTTL(config('api.auth_ttl'))->refresh();
	    	app(AuthOneDevice::class)->auth($user, $token);
    	    return $this->respondWithToken($token);
	    }

	    auth('api')->logout();
	    return response(null, 204);
    }

    public function logout()
    {
    	if ($user = auth('api')->user()) {
    		$user->delFromCache();
	    }

	    auth('api')->logout();
	    return response(null, 204);
    }

    public function destroy()
    {
    	if ($user = auth('api')->user()) {
    		$user->delFromCache();
    		$user->delete();
	    }

    	auth('api')->logout();

    	return response(null, 204);
    }

    protected function respondWithToken(string $token)
    {
    	$expiredAt = auth('api')->factory()->getTTL(); // minutes.
    	return response()->json([
    		'access_token' => $token,
		    'token_type' => 'Bearer',
		    'refresh_at' => ($expiredAt - 14400) * 60, // minus 10 days.
		    'expired_at' => $expiredAt * 60, // seconds.
	    ]);
    }
}
